<?php

declare (strict_types=1);

namespace app\store\model\customer;

use app\store\model\store\User;

/**
 *
 * Class Customer
 * @package app\store\model\customer
 */
class Package extends \app\common\model\customer\Package
{
    /**
     * 检索查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认查询条件
        $param = $this->setQueryDefaultValue($param, [
            'search' => '',
            'customer_id' => '',
            'store_user_id' => '',
            'kj_user_id' => '',
            'wq_user_id' => '',
            'status' => -1,
            'create_time' => []
        ]);
        // 检索查询条件
        $filter = [];
        !empty($param['search']) && $filter[] = ['service_name', 'like', "%{$param['search']}%"];
        !empty($param['customer_id']) && $filter[] = ['customer_id', '=', $param['customer_id']];
        !empty($param['store_user_id']) && $filter[] = ['store_user_id', '=', $param['store_user_id']];
        !empty($param['kj_user_id']) && $filter[] = ['kj_user_id', '=', $param['kj_user_id']];
        !empty($param['wq_user_id']) && $filter[] = ['wq_user_id', '=', $param['wq_user_id']];
        $param['status'] > -1 && $filter[] = ['status', '=', $param['status']];

        if (!empty($param['create_time'])) {
            $times = between_time($param['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    /**
     * 获取列表记录
     * @param array $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = []): \think\Paginator
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 查询列表数据
        return $this->where($filter)
            ->with(['store_user', 'kj_user', 'wq_user', 'customer'])
            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }

    /**
     * 添加新记录
     * @param array $data
     * @return bool|false
     */
    public function adds(array $data, array $store = []): bool
    {
        $data['create_time'] = time();
        $data['store_user_id'] = $store['user']['store_user_id'];
        $data['store_id'] = self::$storeId;
        $this->transaction(function () use ($data, $store) {
            $this->save($data);

            //生成本次套餐服务内容
            if (!empty($data['serviceTable'])) {
                (new Service())->saveList($data['customer_id'], $this->package_id, $data['serviceTable']);
            }

            //生成合同
            $this->generateContract($this->package_id);
        });
        return true;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edits(array $data): bool
    {
        $this->transaction(function () use ($data) {
            if (isset($data['status']) && $data['status'] == 2) {
                $data['audit_time'] = time();
                (new Customer())->where(['customer_id' => $this->customer_id])->save(['customer_type' => 1]);
                $list = (new Service())->where(['package_id' => $this->package_id, 'is_delete' => 0])->select();
                foreach ($list as $item) {
                    if ($item->month > 0) {
                        $item->start_time = time();
                        $time = strtotime("+{$item->month} month");
                        $day = date('d', $time);
                        $item->end_time = strtotime(-$day . ' day', $time);
                        $item->save();
                    }
                }
            }

            $this->save($data);

            //生成本次套餐服务内容
            if (!empty($data['serviceTable'])) {

                //清除已有记录
                (new Service())->where([
                    'customer_id' => $this->customer_id,
                    'package_id' => $this->package_id,
                ])->save(['is_delete' => 1]);
                //添加新记录
                (new Service())->saveList($this->customer_id, $this->package_id, $data['serviceTable']);
            }
            //生成合同
            $this->generateContract($this->package_id);
        });
        return true;
    }


    public function generateContract($package_id = '')
    {
        $package_id = $package_id ? $package_id : $this->package_id;

        //套餐信息
        $package = $this
            ->with(['customer'])
            ->where(['package_id' => $package_id])->find();
        if (!$package || !$package->customer) {
            return false;
        }

        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template/template.docx');

        // 生成表格
        $where = [
            'package_id' => $package_id,
            'is_delete' => 0,
        ];
        $service_list = (new \app\store\model\customer\Service)->where($where)->select();
        $templateProcessor->cloneRow('service_name', count($service_list));
        foreach ($service_list as $k => $item) {
            $id = $k + 1;
            $templateProcessor->setValue("service_name#{$id}", $item->service_name);
            $templateProcessor->setValue("service_price#{$id}", $item->deal_price);
            $templateProcessor->setValue("service_time#{$id}", $item->month ? $item->month . '个月' : "一次性服务");
        }

        $standard_price = (new \app\store\model\customer\Service)->where($where)->sum('deal_price');
        $ledger_expenses = (new \app\store\model\customer\Service)->where($where)->sum('ledger_expenses');


        $admin_info = User::get($package->store_user_id);

        if ($package->customer->customer_identity == 0) {
            $templateProcessor->setValue('full_name', $package->customer->full_name);
            $templateProcessor->setValue('idnumber', $package->customer->idnumber);
            $templateProcessor->setValue('signatory', $package->customer->full_name);
        } else {
            $templateProcessor->setValue('full_name', $package->customer->corporate_name);
            $templateProcessor->setValue('idnumber', null);
            $templateProcessor->setValue('signatory', $package->customer->signatory);
        }

        $templateProcessor->setValue('mobile', $package->customer->mobile);
        $templateProcessor->setValue('admin_name', $admin_info ? $admin_info->real_name : '-');
        $templateProcessor->setValue('admin_mobile', $admin_info ? $admin_info->mobile : '-');
        $templateProcessor->setValue('service_desc', $package->service_desc);
        $templateProcessor->setValue('standard_price', $standard_price);
        $templateProcessor->setValue('total_price', $standard_price);
        $templateProcessor->setValue('ledger_expenses', $ledger_expenses ? $ledger_expenses : '/');
        $templateProcessor->setValue('pay_type1', $package->pay_type == 1 ? '☑' : '☐');
        $templateProcessor->setValue('pay_type2', $package->pay_type == 2 ? '☑' : '☐');

        $templateProcessor->setImageValue('signature1', [
            'path' => 'template/empty.png',
            'width' => 100,
            'height' => 40,
            'ratio' => true
        ]);

        if ($package->signature_url) {
            $templateProcessor->setImageValue('signature', [
                'path' => str_replace('/uploads', 'uploads', $package->signature_url),
                'width' => 100,
                'height' => 40,
                'ratio' => true
            ]);
            if ($package->signature_time) {
                $templateProcessor->setValue('signing_year_time', date("Y", $package->signature_time));
                $templateProcessor->setValue('signing_month_time', date("m", $package->signature_time));
                $templateProcessor->setValue('signing_day_time', date("d", $package->signature_time));
            } else {
                $templateProcessor->setValue('signing_year_time', '    ');
                $templateProcessor->setValue('signing_month_time', '    ');
                $templateProcessor->setValue('signing_day_time', '    ');
            }
        } else {
            $templateProcessor->setImageValue('signature', [
                'path' => 'template/empty.png',
                'width' => 100,
                'height' => 40,
                'ratio' => true
            ]);
            if ($package->audit_time) {
                $templateProcessor->setValue('signing_year_time', date("Y", $package->audit_time));
                $templateProcessor->setValue('signing_month_time', date("m", $package->audit_time));
                $templateProcessor->setValue('signing_day_time', date("d", $package->audit_time));
            } else {
                $templateProcessor->setValue('signing_year_time', '    ');
                $templateProcessor->setValue('signing_month_time', '    ');
                $templateProcessor->setValue('signing_day_time', '    ');
            }
        }
        $contract_url = 'contract/contract_' . $package->package_id . '_' . uniqid() . '_' . time() . '.docx';
        $package->save(['contract_url' => $contract_url]);
        $templateProcessor->saveAs($contract_url);
    }

    /**
     * 删除记录 (软删除)
     * @return bool
     */
    public function setDeleted(): bool
    {
        //删除关联套餐内容
        (new Service())->where(['is_delete' => 0, 'package_id' => $this->package_id])->save(['is_delete' => 1]);
        return $this->save(['is_delete' => 1]) !== false;
    }
}
